<template>
  <div class="register-container">
    <div class="page-header">
      <h2>预约挂号</h2>
    </div>
    
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-radio-group v-model="searchForm.registerStatus">
            <el-radio label="">全部</el-radio>
            <el-radio label="待就诊">待就诊</el-radio>
            <el-radio label="已就诊">已就诊</el-radio>
            <el-radio label="已取消">已取消</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        
        <el-form-item>
          <el-cascader
            v-model="searchForm.departmentIds"
            :options="departmentList"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'departmentName',
              children: 'children',
              emitPath: false
            }"
            placeholder="请选择科室"
            clearable
            style="width: 220px"
            @change="handleDepartmentChange"
          />
        </el-form-item>
        
        <el-form-item>
          <el-input v-model="searchForm.searchName" placeholder="请输入患者姓名" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchRegistrations">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="patientName" label="患者姓名" />
        <el-table-column prop="slot_number" label="就诊卡号" />
        <el-table-column prop="idCardNumber" label="身份证号" />
        <el-table-column prop="phoneNumber" label="手机号码" />
        <el-table-column prop="department" label="挂号科室" />
        <el-table-column prop="doctorName" label="挂号医生" />
        <el-table-column prop="registerType" label="挂号类型" />
        <el-table-column prop="registerFee" label="挂号费用" width="100">
          <template #default="scope">
            {{ scope.row.registerFee }}元
          </template>
        </el-table-column>
        <el-table-column prop="registerStatus" label="挂号状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.registerStatus)">
              {{ scope.row.registerStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerDate" label="预约日期">
          <template #default="scope">
            {{ formatDateTime(scope.row.appointmentTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="就诊时间">
          <template #default="scope">
            {{ formatDateTime(scope.row.registerDate) }}
          </template>
        </el-table-column>
    
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" plain size="small" circle @click="goToDetail(scope.row.id)">
              <el-icon><Edit /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import {axiosrmedical} from '@/http/axiosRead'
import moment from 'moment'
import { useRouter } from 'vue-router'

// 定义科室数据接口
interface Department {
  id: number;
  departmentName: string;
  children?: Department[];
}

// 初始化路由
const router = useRouter()

// 科室列表数据
const departmentList = ref<Department[]>([])

// 搜索表单数据
const searchForm = reactive({
  registerStatus: '',
  dateRange: [],
  consultingRoom: '',
  departmentIds: null as number | null,
  searchName: '',
})

// 处理科室选择变化
const handleDepartmentChange = (value: number) => {
  if (value) {
    // 根据选中的科室ID查找对应的科室名称
    const findDepartmentName = (depts: Department[], id: number): string | null => {
      for (const dept of depts) {
        if (dept.id === id) {
          return dept.departmentName;
        }
        if (dept.children && dept.children.length > 0) {
          const name = findDepartmentName(dept.children, id);
          if (name) return name;
        }
      }
      return null;
    };
    
    const deptName = findDepartmentName(departmentList.value, value);
    if (deptName) {
      searchForm.consultingRoom = deptName;
    }
  } else {
    searchForm.consultingRoom = '';
  }
}

// 日期格式化方法
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  return moment(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

// 表格数据相关
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取科室列表
const fetchDepartments = async () => {
  try {
    console.log('开始获取科室数据')
    const response = await axiosrmedical.get('/Department/GetAllDepartments')
    console.log('科室数据响应:', response.data)
    if (response.data && response.data.code === 200) {
      departmentList.value = response.data.data || []
      console.log('科室列表:', departmentList.value)
    } else {
      ElMessage.error(response.data.msg || '获取科室列表失败')
    }
  } catch (error) {
    console.error('获取科室列表出错:', error)
    ElMessage.error('获取科室列表失败')
  }
}

// 获取挂号状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case '待就诊':
      return 'warning'
    case '已就诊':
      return 'success'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取预约挂号列表数据
const fetchRegistrations = async () => {
  loading.value = true
  try {
    // 构建查询参数 - 使用完整URL（包含端口号）
    let url = `/Register/ShowRegister?PageIndex=${currentPage.value}&PageSize=${pageSize.value}`
    
    // 添加可选参数
    if (searchForm.registerStatus) {
      url += `&Status=${encodeURIComponent(searchForm.registerStatus)}`
    }
    
    if (searchForm.dateRange && searchForm.dateRange.length > 0) {
      const startDate = searchForm.dateRange[0] ? new Date(searchForm.dateRange[0]).toISOString() : null
      const endDate = searchForm.dateRange[1] ? new Date(searchForm.dateRange[1]).toISOString() : null
      
      if (startDate) url += `&StartDate=${encodeURIComponent(startDate)}`
      if (endDate) url += `&EndDate=${encodeURIComponent(endDate)}`
    }
    
    if (searchForm.consultingRoom) {
      url += `&ConsultingRoom=${encodeURIComponent(searchForm.consultingRoom)}`
    }
    
    if (searchForm.searchName) {
      url += `&SearchName=${encodeURIComponent(searchForm.searchName)}`
    }
    
    // API 请求
    const response = await axiosrmedical.get(url)
    
    // 处理响应数据 - 根据接口返回格式调整
    if (response.data && response.data.code === 200) {
      // 映射响应数据到表格所需格式
      tableData.value = (response.data.pageData || []).map((item: any) => ({
        id: item.id,
        patientName: item.patientName,
        patientId: item.patientId,
        medicalCardNumber: item.medicalCardNumber,
        idCardNumber: item.idCardNumber,
        phoneNumber: item.phoneNumber,
        department: item.department,
        departmentId: item.departmentId,
        doctorId: item.doctorId,
        doctorName: item.doctorName,
        registerType: item.registerType,
        registerFee: item.registerFee,
        registerStatus: item.registerStatus,
        registerDate: item.registerDate,
        appointmentTime: item.appointmentTime,
        registrationId: item.registrationId,
        slot_number: item.slot_number,
      
      }))
      total.value = response.data.totaCount || 0
    } else {
      ElMessage.error(response.data.msg || '获取预约挂号数据失败')
    }
  } catch (error) {
    console.error('获取预约挂号数据出错:', error)
    ElMessage.error('获取预约挂号数据出错')
  } finally {
    loading.value = false
  }
}

// 搜索
const searchRegistrations = () => {
  currentPage.value = 1
  fetchRegistrations()
}

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchRegistrations()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchRegistrations()
}

// 跳转到详情页面
const goToDetail = (id: number) => {
  router.push(`/RegisterDetail/${id}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDepartments()
  fetchRegistrations()
})
</script>

<style scoped>
.register-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 